$(document).ready(function() {
	var $calendar = $('#calendar');
	//var maxBookId = 0;
	$calendar.weekCalendar({
		timeslotsPerHour: 2,
		timeFormat: "H:i",
		dateFormat: "Y-m-d",
		use24Hour: true,
		firstDayOfWeek: 1,
		allowCalEventOverlap: true,
		buttonText: {today:"今天", lastWeek:"<", nextWeek: ">"},
		newEventText: "新预约",
		timeSeparator: "～",
		businessHours: {start:8,end:19,limitDisplay:true}, 
		daysToShow: 5,
		longDays: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
		height: function($calendar) {
			return $(window).height() - $("h1").outerHeight()*5 - 1;
		},
		noEvents: function() {},
		draggable: function(calEvent, $event) {
			return false;
		},
		resizable: function(calEvent, $event) {
			return false; //calEvent.readOnly == true;
		},
		eventRender: function(calEvent, $event) {
			if(roomList!=null)
				$event.append('<div>地点：'+getRoomName(calEvent.room)+'<br />预约人：'+userInfo.n+'</div>');
			if (calEvent.v == 0) {
				$event.css("backgroundColor", "#aaa");
				$event.find(".wc-time").css({
					"backgroundColor" : "#999",
					"border" : "1px solid #888"
				});
				
			}
/*			if (calEvent.end.getTime() < new Date().getTime()) {
				$event.css("backgroundColor", "#aaa");
				$event.find(".wc-time").css({
					"backgroundColor" : "#999",
					"border" : "1px solid #888"
				});
			}*/
		},
		eventClick: function(calEvent, $event) {
			if(calEvent.readOnly) return;
			var $dialogContent = $("#event_edit_container");
			resetForm($dialogContent);
			var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
			var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
			var titleField = $dialogContent.find("textarea[name='title']").val(calEvent.title);
			var roomField = $dialogContent.find("select[name='room']");
			var bookid = calEvent.id;
			
			addApprovedOption($dialogContent, calEvent.v);
			
			$dialogContent.dialog({
				modal: true,
				title: "预约修改 - " + calEvent.title,
				close: function() {
					$dialogContent.find("li:last").html('');
					$dialogContent.dialog("destroy");
					$dialogContent.hide();
					$calendar.weekCalendar("removeUnsavedEvents");
				},
				buttons: 
					[{
						text: "更新",
						click: function() {
							calEvent.start = new Date(startField.val());
							calEvent.end = new Date(endField.val());
							calEvent.title = titleField.val();
							calEvent.room = roomField.val();
							
							$calendar.weekCalendar("updateEvent", calEvent);
							$dialogContent.dialog("close");
							$.post("controller/book.php?op=update",getBook(calEvent),
									function(data) { alert(data);}
							);
						},
						disabled: calEvent.not,
						enabled: true
					},{
						text: "删除",
						click: function() {
							$calendar.weekCalendar("removeEvent", calEvent.id);
							$dialogContent.dialog("close");
							$.post("controller/book.php?op=delete",
								{bid:bookid, uid:userInfo.id},
								function(data) { alert(data);}
							);
						},
						disabled: calEvent.not
					},{
						text: "取消",
						click: function() {
							$dialogContent.dialog("close");
						},
						enabled: false
					}]
			}).show();
			
			$dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
			$dialogContent.find(".user_holder").text(calEvent.user);
			setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
			selectRoom(calEvent.room);
		},
		eventMouseover: function(calEvent, $event) {
			
		},
		eventMouseout: function(calEvent, $event) {},
//		eventDrag: function(calEvent, $event) {},
//		eventDrop: function(calEvent, $event) {},
//		eventResize: function(calEvent, $event) {},
		eventNew: function(calEvent, $event) {
			var $dialogContent = $("#event_edit_container");
			resetForm($dialogContent);
			var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
			var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
			var titleField = $dialogContent.find("textarea[name='title']");
			var roomField = $dialogContent.find("select[name='room']");
			
			addApprovedOption($dialogContent, 0);
			
			$dialogContent.dialog({
				modal: true,
				title: "新建会议室预约",
				close: function() {
					$dialogContent.find("li:last").html('');
					$dialogContent.dialog("destroy");
					$dialogContent.hide();
					$calendar.weekCalendar("removeUnsavedEvents");
				},
				buttons: {
					save : function() {
						//calEvent.id = 100;
						calEvent.start = new Date(startField.val());
						calEvent.end = new Date(endField.val());
						calEvent.title = titleField.val();
						calEvent.room = roomField.val();
						
						$calendar.weekCalendar("updateEvent", calEvent);
						$dialogContent.dialog("close");
						$.post("controller/book.php?op=create", getBook(calEvent),
							function(data) {
								alert(data);
								$calendar.weekCalendar("refresh");
						});
					},
					cancel : function() {
						$dialogContent.dialog("close");
					}
				}
			}).show();

			$dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
			$dialogContent.find(".user_holder").text(userInfo.n);
			setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
			selectRoom(0);
		},
//		data: function(start, end, callback) {
//			$.getJSON("controller/book.php?op=index",
//				function(result) {
//					//getMaxBookId(result);
//					//alert(maxBookId);
//					callback(result);
//				});
//		},
		data: "controller/book.php?op=index",
		calendarAfterLoad: function() {
			//$calendar.weekCalendar("refresh");
		},
		calendarBeforeLoad: function() {
			//check the user login or not
			isLogin();	
			// initial the list of room
			loadRoomList();
		}
	});

	


	function resetForm($dialogContent) {
		$dialogContent.find("select").empty();
		$dialogContent.find("textarea").val("");
	}
	
	function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {
		for (var i = 0; i < timeslotTimes.length; i++) {
			var startTime = timeslotTimes[i].start;
			var endTime = timeslotTimes[i].end;
			var startSelected = "";
			if (startTime.getTime() === calEvent.start.getTime()) {
				startSelected = "selected=\"selected\"";
			}
			var endSelected = "";
			if (endTime.getTime() === calEvent.end.getTime()) {
				endSelected = "selected=\"selected\"";
			}

			$startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
			$endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

		}
		$endTimeOptions = $endTimeField.find("option");
		$startTimeField.trigger("change");
	}

	var $endTimeField = $("select[name='end']");
	var $endTimeOptions = $endTimeField.find("option");

	//reduces the end time options to be only after the start time options.
	$("select[name='start']").change(function() {
		var startTime = $(this).find(":selected").val();
		var currentEndTime = $endTimeField.find("option:selected").val();
		$endTimeField.html(
			$endTimeOptions.filter(function() {
				return startTime < $(this).val();
			})
		 );

		var endTimeSelected = false;
		$endTimeField.find("option").each(function() {
			if ($(this).val() === currentEndTime) {
				$(this).attr("selected", "selected");
				endTimeSelected = true;
				return false;
			}
		});

		if (!endTimeSelected) {
			//automatically select an end date 2 slots away.
			$endTimeField.find("option:eq(1)").attr("selected", "selected");
		}

	});
	
	
	
	var $m = $("#menu"),
		$w = $("#window");
	
	var userInfo, roomList;
	
	/**
	 * Initial the page, load data and login.
	 * 
	 */
	//initial the top menu
	$("#l").click(function() {
		userLogout();
	});
	
	$("#re").click(function() {
		$calendar.weekCalendar("refresh");
	});
	
	$("#m").click(function() {
		var page = (userInfo.t==1)?"view/_menu_admin.html":"view/_menu_user.html";
		$m.load(page, function() {
			$("#room_fulllist").click(function() {
				menu_roomList();
			});
			$("#room_create").click(function() {
				menu_roomCreate();
			});
			$("#user_changepwd").click(function() {
				menu_userUpdatePwd();
			});
		});
		$m.dialog({
			title: "菜单中心",
			width: 220,
			resizable: false
		});
	});
	

	/**
	 * **********************************************
	 * ******* Functions of controller 'user' *******
	 * **********************************************
	 */
	
	function isLogin() {
		$.get("controller/user.php?op=stat", function(data) {
			if(!data) userLogin();
			else userInfo = $.parseJSON(data);
		});
	}
	
	function getLoginForm() {
		var name = $("input[name='u_name']"),
			pwd = $("input[name='u_pwd']");
		return $([]).add(name).add(pwd);
	}
	
	function userLogin() {
		$w.load("view/_user_login.html");
		$w.dialog({
			modal: true,
			title: "用户登录",
			resizable: false,
			close: function() {
				$(this).dialog("open");
			},
			buttons: {
				"登陆": function() {
					$.post("controller/user.php?op=login",getLoginForm(),
						function(data) {
							var t;
							switch(data) {
								case "0":
									$w.dialog("destroy");
									$("#calendar").weekCalendar("refresh"); 
									break;
								case "1":
									updateTips("密码错误");
									break;
								case "2":
									updateTips("用户名不存在");
									break;
							}
						}
					);
				}
			}
		});
	}
	
	function updateTips(t) {
		tips = $(".validateTips");
		tips
			.html('<span class="ui-icon" style="float: left; margin-right: .3em;"></span>')
			.append("<p>"+t+"</p>")
			.addClass("ui-state-error");
		$(".validateTips span").addClass("ui-icon-alert");
		setTimeout(function() {
			tips.removeClass("ui-state-error", 1500);
			tips.html('');
		}, 3500 );
	}
	
	function userLogout() {
		$.get("controller/user.php?op=logout", function(data) {
			//alert(data);
			$m.dialog("destroy");
			$w.dialog("destroy");
			userLogin();
		});
	}
	
	function getUpFormData() {
		var pwd = $("input[name='u_pwd']"),
			npwd = $("input[name='u_newpwd']");
		return $([]).add(pwd).add(npwd);
	}
	
	function validateUpForm() {
		var pwd = $("input[name='u_pwd']").val(),
			npwd = $("input[name='u_newpwd']").val(),
			repwd = $("input[name='u_repwd']").val();
		if(pwd=="") {
			updateTips("当前密码不能为空");
			return false;
		}else if(npwd=="") {
			updateTips("新密码不能为空！");
			return false;
		}else if(npwd!=repwd) {
			updateTips("两次密码输入不一致！");
			return false;
		}else if(pwd==npwd) {
			updateTips("新密码与当前密码一样！");
			return false;
		}else return true;
	}
	
	function switchUpReturnValue(rv) {
		switch(rv) {
		case '0':
			alert("密码修改成功，请使用新密码重新登录！");
			userLogout();
			break;
		case '1':
			updateTips("当前密码输入错误！");
			break;
		case '2':
			updateTips("新密码不能为空！");
			break;
		}
	} 
	
	function menu_userUpdatePwd() {
		$m.dialog("close");
		$w.load("view/_user_updatepwd.html")
		.ajaxComplete(function() {
			$(".u_user").text(userInfo.u);
			$(".u_name").text(userInfo.n);
		})
		.dialog({
			modal: true,
			title: "修改密码",
			resizable: false,
			close: function() {
				$(this).dialog("destroy");
				$m.dialog("open");
			},
			buttons: {
				"修改": function() {
					if(validateUpForm()) {
						$.post("controller/user.php?op=up",getUpFormData(),
							function(data) {
								//alert(data);
								switchUpReturnValue(data);
							}
						);
					}
				},
				"取消": function() {
					$(this).dialog("close");
				}
			}
		}).show();
	}
	
	/**
	 * **********************************************
	 * ******* Functions of controller 'room' *******
	 * **********************************************
	 */

	function loadRoomList() {
		$.getJSON("controller/room.php?op=index",
			function(data) {
				roomList = data;
			}
		);
		
	}
	
	function getRoomName(rid) {
		var name;
		$.each(roomList, function(i,r) {
			if(rid==r.id)
				name = r.title;
		});
		return name;
	}
	
	function selectRoom(rid) {
		$.each(roomList, function(index,room) {
			if(rid==room.id)
				$("select[name='room']").append("<option value=\""+room.id+"\" selected=\"selected\">"+room.title+"</option>");
			else
				$("select[name='room']").append("<option value=\""+room.id+"\">"+room.title+"</option>");
		});
//		$.getJSON("controller/room.php?op=index",function(data) {
//			$.each(data, function(index,room) {
////				if(room.media) $media="是";
////				else $media="否";
//				$("#newwin").button();
//				$("#newwin").click(function() {
//					
//					$w.html("<p>asdf</p>");
//					$w.dialog({
//						title: room.title,
//						width: 100,
//						height: 200,
//						close: function() {
//							$(this).dialog("destroy");
//						}
//					}).show();
////					$w.position({
////						of: $("#event_edit_container"),
////						my: "left center",
////						at: "right center"
////					});
//					//return false;
//				});
//				if(id==room.id)
//					$("select[name='room']").append("<option value=\""+room.id+"\" selected=\"selected\">"+room.title+"</option>");
//				else
//					$("select[name='room']").append("<option value=\""+room.id+"\">"+room.title+"</option>");
//			});
//		});
	}
	
	function tableRoomList(){
		var tablerow = "";
		$.each(roomList, function(index,room) {
			if(room.media==1) $media="是";
			else $media="否";
			//$("#r_list tbody").append("<tr>"+"<td>"+room.id+"</td>"+"<td>"+room.title+"</td>"+"<td>"+room.num+"</td>"+"<td>"+$media+"</td>"+"<td>"+"<a href='#'>删除</a>"+"</td>"+"</tr>");
			tablerow = tablerow + "<tr>"+"<td>"+room.id+"</td>"+"<td>"+room.title+"</td>"+"<td>"+room.num+"</td>"+"<td>"+$media+"</td>"+"<td>"+"<a href='#'>删除</a>"+"</td>"+"</tr>";
		});
		$("#r_list tbody").html(tablerow);
//		$("#r_list a").click(function() {
//			var index = $("#r_list a").index($(this));
//			var id = $("#r_list td:eq("+index*5+")").text();
//			$.get("controller/room.php?op=delete&id="+id, function(data) {
//				alert(data);
//			});
//		});
	}
	
	function menu_roomList() {
		$m.dialog("close");
		$w
			.load("view/_room_list.html")
			.ajaxComplete(function() {
				tableRoomList();
			})
			.dialog({
				modal: true,
				title: "会议室列表",
				width: 480,
				resizable: true,
				close: function() {
					$(this).dialog("destroy");
					$m.dialog("open");
				},
				buttons: {
					"返回": function() {
						$(this).dialog("close");
					},
					"test": function() {
						alert(userInfo.n);
					}
				}
				
			}).show();
	}
	
	function getRoom() {
		var name = $("input[name='r_name']"),
			vol = $("input[name='r_vol']"),
			media = $("input[name='r_media']:checked");
		return $([]).add(name).add(vol).add(media);
	}
	
	function menu_roomCreate() {
		$m.dialog("close");
		$w.load("view/_room_create.html");
		$w.dialog({
			modal: true,
			title: "新增会议室",
			//height: 350,
			resizable: false,
			close: function() {
				$(this).dialog("destroy");
				$m.dialog("open");
			},
			buttons: {
				"保存": function() {
					$.post("controller/room.php?op=create",getRoom(),
						function(data) {
							alert(data);
							loadRoomList();
							$w.dialog("close");
						}
					);
				},
				"取消": function() {
					$(this).dialog("close");
				}
			}
			
		}).show();
	}
	
	/**
	 * **********************************************
	 * ******* Functions of controller 'book' *******
	 * **********************************************
	 */
	function getBook(calEvent) {
		var res = {};
		res.uid = userInfo.id;
		res.bid = calEvent.id;
		var starttime = new Date($("select[name='start']").val());
		var endtime = new Date($("select[name='end']").val());
		res.start = starttime.toUTCString();
		res.end = endtime.toUTCString();
		res.room = $("select[name='room']").val();
		res.title = $("textarea[name='title']").val();
		return res;
	}
	
	
	function getMaxBookId(data) {
		for (var i = 0; i < data.length; i++) {
			if(data[i].id > maxBookId) maxBookId = data[i].id;
		}
	}
	
	
	
	
	
	/**
	 * ************
	 * * Approved *
	 * ************
	 */
	
	function addApprovedOption($dialogContent,vType) {
		var approvename = new Array("未审核","通过","拒绝");
		var approveoptions = '<label>审核：'+vType+'</label>';
		var ch = '';
		for(var i = 0; i < 3; i++) {
			if(i==vType) {ch = ' checked="checked"';}
			else ch = '';
			approveoptions = approveoptions + '<input type="radio" name="approve" value="' + i + '"' + ch + ' /><span>' + approvename[i] + '</span>';
		}
		//approveoptions = approveoptions + '</li>';
		if(userInfo.t==1) $dialogContent.find("li:last").append(approveoptions);
	}
	
});